/*
 * FileMap.cpp
 *
 *  Created on: 2013年8月21日
 *      Author: sun
 */

#include "FileMap.h"
#include "tracker_global.h"

namespace sdfs {

const FileMap *FileMap::instance = NULL;

FileMap::FileMap(int size) {
	if(instance != NULL)
		return;
	m_size = size;
	RedisAdaptor adaptor(p_db_config);
	m_db_pool = new ConnectionPool(&adaptor, size);
	instance = this;
}

FileMap *FileMap::GetInstance()
{
	return (FileMap *)instance;
}


FileMap::~FileMap() {
	delete m_db_pool;
}

void FileMap::GetFileRecord(RedisReply &reply, const char *hashcode)
{
	RedisAdaptor *pAdaptor = (RedisAdaptor *)m_db_pool->GetConnection();
	if(pAdaptor != NULL)
	{
		pAdaptor->Command(reply, "LRANGE %s 0 -1", hashcode);
	}
	m_db_pool->ReturnConnection(pAdaptor);
}

struct fileInfo* FileMap::GetFileInfo(RedisReply &reply)
{
	if(reply.Type() == REDIS_REPLY_ARRAY && reply.Array_size() > 0)
		return (struct fileInfo *)reply.Array_at(0)->str;
	return NULL;
}

struct blockInfo* FileMap::GetBlockInfoAt(RedisReply &reply, int idx)
{
	if(reply.Type() != REDIS_REPLY_ARRAY)
		return NULL;
	if(idx < 0 || idx >= reply.Array_size())
		return NULL;
	return (struct blockInfo *)reply.Array_at(idx)->str;
}

size_t	FileMap::GetBlockCount(RedisReply &reply)
{
	return reply.Array_size()-1;
}

int FileMap::AddFileInfo(struct fileInfo *info, int size)
{
	RedisReply reply;
	RedisAdaptor *pAdaptor = (RedisAdaptor *)m_db_pool->GetConnection();
	pAdaptor->Command(reply, "RPUSH %s %b", info->hashcode, size);
	m_db_pool->ReturnConnection(pAdaptor);
	if(strcmp("OK",reply.Str())== 0)
		return 0;
	return 1;
}

int FileMap::RemoveFileInfo(const char *hashcode)
{
	RedisReply reply;
	RedisAdaptor *pAdaptor = (RedisAdaptor *)m_db_pool->GetConnection();
	pAdaptor->Command(reply, "DEL %s", hashcode);
	m_db_pool->ReturnConnection(pAdaptor);
	if(reply.Integer() > 0)
		return 0;
	return 1;
}

int FileMap::AddBlockInfo(const char *hashcode, struct blockInfo *info, int size)
{
	RedisReply reply;
	RedisAdaptor *pAdaptor = (RedisAdaptor *)m_db_pool->GetConnection();
	pAdaptor->Command(reply, "RPUSH %s %d", hashcode, info, size);
	m_db_pool->ReturnConnection(pAdaptor);
	if(reply.Integer() > 0)
		return 0;
	return 1;
}

void FileMap::Close()
{
	RedisAdaptor *pAdaptor;
	RedisReply reply;
	pAdaptor = (RedisAdaptor *)m_db_pool->GetConnection();
	do{
		pAdaptor->DisConnect();
		pAdaptor = (RedisAdaptor *)m_db_pool->GetConnection();
	}while(pAdaptor != NULL);
}

} /* namespace sdfs */
